package org.javaboy.business.service;

import io.seata.core.context.RootContext;
import io.seata.rm.tcc.api.BusinessActionContext;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BusinessService {

    @Autowired
    OrderService orderService;
    @Autowired
    StorageService storageService;

    @GlobalTransactional
    public String buy(Integer userId, Integer commodityCode, Integer count) {
        //获取整个分布式事务的全局id
        String xid = RootContext.getXID();
        BusinessActionContext businessActionContext = new BusinessActionContext();
        businessActionContext.setXid(xid);
        //如果这个方法执行失败会自动抛出异常，那么后续就不需要自己手动抛异常了
        boolean r1 = storageService.deduceStorage(businessActionContext, commodityCode, count);
        if (!r1) {
            throw new RuntimeException("扣减库存失败");
        }
        boolean r2 = orderService.createOrder(businessActionContext, userId, commodityCode, count);
        if (!r2) {
            throw new RuntimeException("创建订单失败");
        }
        return "success";
    }
}
